from datetime import datetime

from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.views import JSONWebTokenAPIView
# Create your views here.
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.serializers import JSONWebTokenSerializer

from system import models

jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER


class LoginView(JSONWebTokenAPIView):
    """
    登录接口的逻辑
    """
    serializer_class = JSONWebTokenSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            print(user, request.user)
            expires = datetime.now() + api_settings.JWT_EXPIRATION_DELTA
            models.UserInfo.objects.filter(username=user).update(token=token,
                                                                 expires=expires)
            response_data = jwt_response_payload_handler(token, user, request)
            response_data['expires'] = expires
            return Response(response_data)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class LogoutView(APIView):

    def post(self, request):
        userinfo = request.user
        userinfo.token = ""
        userinfo.expires = None
        userinfo.save()
        return Response("ok")
